/*
 * Copyright kingbi. 
 * Creator: mouzb
 */
package com.kingbi.util.jsf;

import java.util.Hashtable;
import java.util.Map;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;


/**
 * @author mouzb
 *
 */
public class RegexValidator implements Validator {
	/**
	 *	已经编译过的正则表达式的缓冲
	 */
	private static Map<String,Pattern> compiledRegexs=new Hashtable<String,Pattern>();
	public static String EMAIL="";
	public static String URL="";
	
	/* 
	 * @see javax.faces.validator.Validator#validate(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
	 */
	public void validate(FacesContext ctxt, UIComponent uic, Object value)
			throws ValidatorException {
		String patternId=(String)uic.getAttributes().get("patternId");
		String pattern=(String)uic.getAttributes().get("pattern");
		if(patternId!=null){
		}else if(pattern!=null){
			if(validate((String)value,pattern)){
				return;
			}
		}
		throw new ValidatorException(new FacesMessage("您输入的数据不符合要求"));
	}
	
	private boolean validate(String string,String pattern){
		Pattern p=null;
		if(compiledRegexs.containsKey(pattern)){
			p=compiledRegexs.get(pattern);
		}else{
			p=Pattern.compile(pattern);
			compiledRegexs.put(pattern, p);
		}
		return p.matcher(string).matches();
	}
}
